package logic

import (
	"11.22/model/mysql"
	"11.22/model/redis"
	"11.22/pkg"
	"11.22/userrpc/internal/svc"
	"11.22/userrpc/userrpc"
	"context"
	"fmt"
	"gorm.io/gorm"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateLogic) Update(in *userrpc.UpdateRequest) (*userrpc.UpdateResponse, error) {
	// todo: add your logic here and delete this line
	get := redis.Rdb.Get("captchaupdate" + in.Account)
	if get.Val() != in.CaptchaCode {
		return nil, fmt.Errorf("验证码错误，请从新输入")
	}

	cmd := redis.Rdb.Get("sendSmsupdate" + in.Account)
	if cmd.Val() != in.SendSmsCode {
		return nil, fmt.Errorf("手机验证码错误，请从新输入")
	}

	var users mysql.User
	mysql.DB.Debug().Where("account = ?", in.Account).Find(&users)

	if users.ID == 0 {
		return nil, fmt.Errorf("账号未注册，请先注册账号")
	}

	if users.Phone == pkg.Md5Pwd(in.Phone) {
		return nil, fmt.Errorf("密码不能相同，请从新输入")
	}
	user := mysql.User{
		Model:   gorm.Model{ID: uint(in.Id)},
		Account: in.Account,
		Phone:   pkg.Md5Pwd(in.Password),
	}
	mysql.DB.Debug().Updates(&user)
	return &userrpc.UpdateResponse{Id: int64(users.ID)}, nil
}
